package com.cxl.demo;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Iterator;

public class NioSocket {
    private static CharsetEncoder encoder = Charset.forName("utf-8").newEncoder();
    private static CharsetDecoder decoder = Charset.forName("utf-8").newDecoder();
    private static ByteBuffer byteBuffer;
    private static Selector selector;
    public static void main(String[] args) {
        init();
    }
    private static void init(){
        byteBuffer = ByteBuffer.allocate(1024); // 缓冲区
        ServerSocketChannel serverSocketChannel  = null;
        try{
            serverSocketChannel = ServerSocketChannel.open(); // 打开一个channel
            serverSocketChannel.configureBlocking(false); // 配置为非阻塞
            serverSocketChannel.socket().bind(new InetSocketAddress(9000),100); // 绑定端口 且 设置队列最大长度
            selector = Selector.open(); // 打开selector
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); // channel绑定到selector上，接收请求

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private static void listen(){
        while (true){
            try {
                selector.select();// 监听连接
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();

                while (iterator.hasNext()){
                    SelectionKey key   = (SelectionKey)iterator.next();
                    iterator.remove();
                    handle(key);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    private static void handle(SelectionKey key){
        SocketChannel socketChannel = null;
        try{

            if (key.isAcceptable()){// 连接请求
                ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                socketChannel = serverSocketChannel.accept();
                socketChannel.configureBlocking(false);
                socketChannel.register(selector,SelectionKey.OP_READ);
            }else if (key.isReadable()){ // 客户端发送了数据过来
                socketChannel = (SocketChannel) key.channel();
                byteBuffer.clear();
                int count  = socketChannel.read(byteBuffer);
                if (count>0){
                    byteBuffer.flip(); // 复位position
                    CharBuffer charBuffer = decoder.decode(byteBuffer);

                    System.out.println("收到数据:"+charBuffer.toString());
                    socketChannel.write(encoder.encode(CharBuffer.wrap("收到".toCharArray())));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
